package com.lxh.empwork.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory factory;
    public static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();

    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T getMapper(Class<T> cla){
        return getSession().getMapper(cla);
    }

    //获取链接
    public static SqlSession getSession(){
        SqlSession session = THREAD_LOCAL.get();
        try {
            if(session == null){
                session = factory.openSession();
                THREAD_LOCAL.set(session);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return session;
    }

    //关闭链接
    public static void close(SqlSession session){
        try {
            session.close();
        } finally {
            THREAD_LOCAL.remove();
        }
    }

    //事务提交
    public static void commit(){
        SqlSession session = getSession();
        session.commit();
        close(session);
    }

    //事务回滚
    public static void rollback(){
        SqlSession session = getSession();
        session.rollback();
        close(session);
    }
}
